/**
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ConfigData, LogUtil, TraceEntry, GlobalContext } from '@common/utils';
import audio from '@ohos.multimedia.audio';

const groupId = audio.DEFAULT_VOLUME_GROUP_ID;

function getAudioManager() {
  console.time('audioManager');
  let audioManager = GlobalContext.getContext().getObject<audio.AudioManager>(GlobalContext.globalKeyAudioManager);
  if (audioManager == undefined) {
    let man = audio.getAudioManager();
    GlobalContext.getContext().setObject(GlobalContext.globalKeyAudioManager, man);
    console.timeEnd('audioManager');
    return man;
  }
  console.timeEnd('audioManager');
  return audioManager;
}

function getAudioVolumeGroupManager(audioManager?: audio.AudioManager): audio.AudioVolumeGroupManager {
  console.time('audioVolumeGroupManager');
  if (audioManager == undefined) {
    audioManager = getAudioManager();
  }
  let avGroupManager =
    GlobalContext.getContext().getObject<audio.AudioVolumeGroupManager>(GlobalContext.globalKeyAudioVolumeGroupManager);
  if (avGroupManager == undefined) {
    const vgMan = audioManager.getVolumeManager().getVolumeGroupManagerSync(groupId);
    GlobalContext.getContext().setObject(GlobalContext.globalKeyAudioVolumeGroupManager, vgMan);
    console.timeEnd('audioVolumeGroupManager');
    return vgMan;
  }
  console.timeEnd('audioVolumeGroupManager');
  return avGroupManager;
}

export async function registerObserver() {
  try {
    console.time('registerObserver');
    console.log('registerObserver');
    // let audioManager = getAudioManager();
    // console.time('audioVolumeGroupManager.on');
    // console.log('audioVolumeGroupManager.on');
    // let audioVolumeGroupManager =
    //   audioManager.getVolumeManager().getVolumeGroupManagerSync(audio.DEFAULT_INTERRUPT_GROUP_ID);
    // audioVolumeGroupManager.on('ringerModeChange', (mode) => {
    //   AppStorage.setOrCreate('ringerModeSilent', mode === audio.AudioRingMode.RINGER_MODE_SILENT);
    //   AppStorage.setOrCreate('ringerModeNormal', mode === audio.AudioRingMode.RINGER_MODE_NORMAL);
    // })
    // console.timeEnd('audioVolumeGroupManager.on')

    // console.time('audioVolumeManager.on')
    // console.log('audioVolumeManager.on')
    // let audioVolumeManager = audioManager.getVolumeManager();
    // audioVolumeManager.on('volumeChange', (data) => {
    //   if (data.volumeType === audio.AudioVolumeType.RINGTONE) {
    //     AppStorage.setOrCreate('volume_ringtone', data.volume);
    //   } else if (data.volumeType === audio.AudioVolumeType.VOICE_CALL) {
    //     AppStorage.setOrCreate('volume_voicecall', data.volume);
    //   } else if (data.volumeType === audio.AudioVolumeType.MEDIA) {
    //     AppStorage.setOrCreate('volume_media', data.volume);
    //   }
    // })
    // console.timeEnd('audioVolumeManager.on')

    // console.time('routingManager.on')
    // console.log('routingManager.on')
    // let routingManager = audioManager.getRoutingManager();
    // routingManager.on('deviceChange', audio.DeviceFlag.ALL_DEVICES_FLAG, () => {
    //   audioVolumeGroupManager.getVolume(audio.AudioVolumeType.RINGTONE, (err, data) => {
    //     AppStorage.setOrCreate('volume_ringtone', data);
    //   })
    //   audioVolumeGroupManager.getVolume(audio.AudioVolumeType.VOICE_CALL, (err, data) => {
    //     AppStorage.setOrCreate('volume_voicecall', data);
    //   })
    //   audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err, data) => {
    //     AppStorage.setOrCreate('volume_media', data);
    //   })
    // })
    // console.timeEnd('routingManager.on')
    console.timeEnd('registerObserver');
  } catch (e) {
    LogUtil.error('Error registerObserver ' + JSON.stringify(e))
  }
}


export class VolumeModel {
  private volumeType;
  private audioManager;
  private volume;
  private TAG = ConfigData.TAG + 'VolumeModel ';
  private oldVolume;

  constructor(volumeType) {
    this.volumeType = volumeType;
    this.audioManager = getAudioManager();
    this.audioManager.getVolume(this.volumeType, (err, data) => {
      this.initState(data);
      this.oldVolume = data;
    })
  }

  /**
   * Get volume value in the VolumeModel
   */
  @TraceEntry
  public initState(volume) {
    if (this.volumeType === audio.AudioVolumeType.RINGTONE) {
      AppStorage.setOrCreate('volume_ringtone', volume);
    } else if (this.volumeType === audio.AudioVolumeType.MEDIA) {
      AppStorage.setOrCreate('volume_media', volume);
    } else if (this.volumeType === audio.AudioVolumeType.VOICE_CALL) {
      AppStorage.setOrCreate('volume_voicecall', volume);
    }
    return;
  }

  /**
   * Set value
   */
  public setVolume(volume: number) {
    if (volume === this.oldVolume) {
      return;
    }
    LogUtil.info(`${this.TAG} setVolume start, volume: ${volume}`);
    this.audioManager.setVolume(this.volumeType, volume).then(() => {
      LogUtil.info(`${this.TAG} setVolume callback in, volume: ${volume}`);
    });
    this.oldVolume = volume;
    LogUtil.info(`${this.TAG} setVolume end, volume: ${volume}`);
  }
}

export class RingerModel {
  private modeTag;
  private TAG = ConfigData.TAG + 'RingerModel ';

  constructor(mode) {
    this.modeTag = mode;
    this.initState();
  }

  /**
   * Update ringer Mode
   */
  public async initState() {
    console.time('initState ringer');
    let audioVolumeGroupManager = getAudioVolumeGroupManager();
    audioVolumeGroupManager.getRingerMode((error, action) => {
      LogUtil.info(`${this.TAG} updateMode.`);
      if (error) {
        return;
      }
      AppStorage.setOrCreate('ringerModeSilent', action === audio.AudioRingMode.RINGER_MODE_SILENT);
      AppStorage.setOrCreate('ringerModeNormal', action === audio.AudioRingMode.RINGER_MODE_NORMAL);
      LogUtil.info(`${this.TAG} updateMode sucess.`);
      console.timeEnd('initState ringer');
    });
  }

  /**
   * Set  ringer mode
   */
  public async setRingerMode() {
    let audioVolumeGroupManager = getAudioVolumeGroupManager();
    audioVolumeGroupManager.setRingerMode(this.modeTag, (err, data) => {
      LogUtil.info(`${this.TAG} setRingerMode.`);
      LogUtil.info(`${this.TAG} setRingerMode sucess.`);
    });
    return;
  }
}

